package com.itheima.app.manager;

import cn.hutool.core.collection.CollectionUtil;
import com.itheima.app.interceptor.UserHolder;
import com.itheima.domain.db.*;
import com.itheima.service.db.SoulTestService;
import com.itheima.service.db.UserInfoService;
import com.itheima.vo.OptionsVo;
import com.itheima.vo.QuestionnaireReportVo;
import com.itheima.vo.QuestionnaireVo;
import com.itheima.vo.SoulQuestionVo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Component
public class SoulTestManager {

    @DubboReference
    private SoulTestService soulTestService;

    public  ResponseEntity testSoul() {
        //最终返回一个 voList
        List<QuestionnaireVo> voList = new ArrayList<>();
        //先遍历出所有的调查问卷
        List<Questionnaire> questionnaireList = soulTestService.findAllQuestionnaire();
        //判断非空 遍历
        if (CollectionUtil.isNotEmpty(questionnaireList)) {
            for (Questionnaire questionnaire : questionnaireList) {
                //新建QuestionnaireVo  3个应该是
                QuestionnaireVo vo = new QuestionnaireVo();
                //set questionnaire 的相关属性
                vo.setQuestionnaire(questionnaire);


                //对于每个调查问卷都有对应的试题
                List<SoulQuestion> soulQuestionList = soulTestService.findByQuestionnaireId(questionnaire.getId());
                //对于每套题中的每道题都有对应的答案
                List<SoulQuestionVo> soulQuestionVoList = new ArrayList<>();
                if (CollectionUtil.isNotEmpty(soulQuestionList)) {
                    for (SoulQuestion soulQuestion : soulQuestionList) {
                        //每个问题的内容封装成vo
                        SoulQuestionVo soulQuestionVo = new SoulQuestionVo();
                        soulQuestionVo.setId(soulQuestion.getId().toString());
                        soulQuestionVo.setQuestion(soulQuestion.getStem());
                        //soulQuestionVo.set Options 对于每道题都有对应的答案
                        List<SoulQuestionOption> soulQuestionOptionList = soulTestService.findBySoulQuestionId(soulQuestion.getId());
                        //对于每个答案 都有对应的vo
                        List<OptionsVo> optionsVoList = new ArrayList<>();
                        for (SoulQuestionOption soulQuestionOption : soulQuestionOptionList) {
                            OptionsVo optionsVo = new OptionsVo();
                            optionsVo.setId(soulQuestionOption.getId().toString());
                            optionsVo.setOption(soulQuestionOption.getContent());
                            optionsVoList.add(optionsVo);
                        }
                        soulQuestionVo.setOptions(optionsVoList);

                        soulQuestionVoList.add(soulQuestionVo);

                    }
                }

                vo.setQuestions(soulQuestionVoList);

                //vo还剩下锁 和 报告id
                //查询userlock
                Long userId = UserHolder.get().getId();
                QuestionUserLock userLock = soulTestService.findByUserId(userId,questionnaire.getId());
                //如果没查到 就新建 如果是第一个就 使lock为0 剩下的为1
                if (userLock == null) {
                    //新建userLock 并set属性
                    userLock = new QuestionUserLock();
                    userLock.setQuestionnaireId(questionnaire.getId());
                    userLock.setUserId(userId);

                    if (questionnaire.getId() == 1) {
                        userLock.setIsLock(0);
                    } else {
                        userLock.setIsLock(1);
                    }
                    soulTestService.saveQuestionUserLock(userLock);
                }
                vo.setIsLock(userLock.getIsLock());

                //reportid  set不set 呢 ？  根据userId 查一下 并且时间倒叙哈
                QuestionnaireReport report = soulTestService.findReportByUserId2(userId);
                if (report != null) {
                    QuestionnaireResult result = soulTestService.findResultById(report.getConclusionId());
                    if (result.getQuestionnaireId() == questionnaire.getId()) {
                        vo.setReportId(report.getId().toString());
                    }
                }



                voList.add(vo);
            }
        }
        return ResponseEntity.ok(voList);

    }


    //根据问题 结果id 新建一份报告 存入数据库 并返回报告id
    public ResponseEntity commit(List<Answer> answerList) {
        //初始化分数
        int score = 0;
        //初始化调查问卷id
        Integer questionnaireId = null;


        for (Answer answer : answerList) {
            Integer optionId = answer.getOptionId();
            //对于每个answer 获取对应的选项

            SoulQuestionOption soulQuestionOption = soulTestService.findBySoulQuestionIdAndOptionId(optionId);
            //根据其中一个问题查到调查w
            SoulQuestion soulQuestion = soulTestService.findByQuestionId(answer.getQuestionId());
            questionnaireId = soulQuestion.getQuestionnaireId();
            score += soulQuestionOption.getScore();
        }


        //根据分数和调查问卷id 查result结果
        QuestionnaireResult questionnaireResult = soulTestService.findByScoreAndQuestionnaireId(questionnaireId,score);

        //查一下report 如果之前存在的话就更新 不存在 再保存
        Long userId = UserHolder.get().getId();
        QuestionnaireReport reportByUserId = soulTestService.findReportByUserId(userId, questionnaireResult.getId());

        Integer id;
        if (reportByUserId == null) {
            QuestionnaireReport report = new QuestionnaireReport();
            //set userId resultId cover

            report.setUserId(userId);
            report.setCover(questionnaireResult.getCover());
            report.setConclusionId(questionnaireResult.getId());
            //把report 存到表里

            id = soulTestService.saveReport(report);
        } else {
            id = reportByUserId.getId();
        }

        //把用户和调查问卷id 对应关系
        //查出下一级的userLock 并且修修改改 使下一等级的调查问卷 lock为0
        QuestionUserLock userLock = soulTestService.findByUserId(userId, questionnaireId+1);
        if (userLock != null) {
            userLock.setIsLock(0);

            soulTestService.updateUserLock(userLock);
        }


        //返回一个reportId
        return ResponseEntity.ok(id.toString());
    }

    @DubboReference
    private UserInfoService userInfoService;

    public ResponseEntity findReport(Integer id) {

        //根据参数id 查找report
        QuestionnaireReport report = soulTestService.findById(id);
        //新建reportVo 然后封装
        QuestionnaireReportVo vo = new QuestionnaireReportVo();
        QuestionnaireResult result = soulTestService.findResultById(report.getConclusionId());
        vo.setConclusion(result.getContent());
        vo.setCover(report.getCover());


        List<Dimension> dimensionList = new ArrayList<>();
        Integer abstraction = report.getAbstraction();
        Integer extroversion = report.getExtroversion();
        Integer judgement = report.getJudgement();
        Integer retionality = report.getRetionality();


        dimensionList.add(new Dimension("abstraction", abstraction.toString()));
        dimensionList.add(new Dimension("extroversion", extroversion.toString()));
        dimensionList.add(new Dimension("judgement", judgement.toString()));
        dimensionList.add(new Dimension("retionality", retionality.toString()));
        vo.setDimensions(dimensionList);

        List<QuestionnaireReport> reportList = soulTestService.findByconclusionId(report.getConclusionId());

        List<SimilarYou> similarYouList = new ArrayList<>();
        for (QuestionnaireReport report1 : reportList) {
            Long userId = report1.getUserId();
            String avatar = userInfoService.findByUserId(userId).getAvatar();
            int userid = Integer.parseInt(userId.toString());
            similarYouList.add(new SimilarYou(userid, avatar));
        }
        vo.setSimilarYou(similarYouList);
        return ResponseEntity.ok(vo);
    }
}
